package cn.house.houseai.interceptor;

import cn.house.houseai.context.BaseContext;

import cn.house.houseai.properties.JwtProperties;
import cn.house.houseai.tools.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author 羡y
 * @date 2024/9/27
 * @Description
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("当前线程的id = " + Thread.currentThread().getId());
        System.out.println("获取到的请求头: " + request.getHeader("Authorization"));

        // 打印所有请求头以帮助调试
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + request.getHeader(headerName));
        }

        // 检查请求头中是否包含 token
        String token = request.getHeader(jwtProperties.getUserTokenName());
        log.info("从请求头获取到的 token: {}", token);

        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            return true; // 当前拦截到的不是动态方法，直接放行
        }

        // 校验 Token
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get("user_id").toString());
            log.info("当前用户id：{}", userId);
            BaseContext.setCurrentId(userId); // 设置当前用户ID
            return true; // 校验通过，放行
        } catch (Exception ex) {
            log.error("Token 校验失败: {}", ex.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            return false; // 校验不通过，拦截请求
        }
    }
}